<template>
  <div class="system-settings-root">
    <el-tabs v-model="activeTab" class="settings-tabs">
      <el-tab-pane label="系统参数设置" name="params">
        <div class="card-block">
          <div class="card-header">
            <span class="card-title">系统参数设置</span>
            <el-button type="primary" @click="openAddParam">新增参数</el-button>
          </div>
          <el-table :data="pagedParams" class="settings-table" :header-cell-style="tableHeaderStyle" :cell-style="tableCellStyle" border stripe>
            <el-table-column prop="code" label="编码" />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="value" label="值" />
            <el-table-column prop="description" label="说明" />
            <el-table-column prop="effectiveRange" label="生效范围" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="primary" link @click="editParam(scope.row)">编辑</el-button>
                <el-button type="danger" link @click="deleteParam(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="table-pagination"
            :current-page="paramPage.pageNum"
            :page-size="paramPage.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="filteredParams.length"
            layout="total, prev, pager, sizes, jumper"
            @size-change="val => { paramPage.pageSize = val; paramPage.pageNum = 1; }"
            @current-change="val => paramPage.pageNum = val"
          />
        </div>
        <el-dialog v-model="showParamDialog" :title="paramDialogTitle" width="400px">
          <el-form :model="paramForm" label-width="90px">
            <el-form-item label="参数编码" required>
              <el-input v-model="paramForm.code" :disabled="!!editingParam" />
            </el-form-item>
            <el-form-item label="参数名称" required>
              <el-input v-model="paramForm.name" />
            </el-form-item>
            <el-form-item label="参数值" required>
              <el-input v-model="paramForm.value" />
            </el-form-item>
            <el-form-item label="说明">
              <el-input v-model="paramForm.description" />
            </el-form-item>
            <el-form-item label="生效范围">
              <el-input v-model="paramForm.effectiveRange" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showParamDialog = false">取消</el-button>
            <el-button type="primary" @click="saveParam">保存</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="数据备份与恢复" name="backup">
        <div class="card-block">
          <div class="card-title">备份策略</div>
          <div class="backup-strategy-form">
            <div class="form-item">
              <span class="form-label">备份周期</span>
              <el-select v-model="backupStrategy.cycle" style="width: 120px">
                <el-option label="每日" value="每日" />
                <el-option label="每周" value="每周" />
                <el-option label="每月" value="每月" />
              </el-select>
            </div>
            <div class="form-item">
              <span class="form-label">备份时间</span>
              <el-time-picker v-model="backupStrategy.time" format="HH:mm" value-format="HH:mm" style="width: 120px" />
            </div>
            <div class="form-item form-btns">
              <el-button type="primary" @click="handleBackup">立即备份</el-button>
              <el-button type="success" @click="handleRestore">恢复数据</el-button>
            </div>
          </div>
        </div>
        <div class="card-block mt-4">
          <el-table :data="pagedBackups" class="settings-table" :header-cell-style="tableHeaderStyle" :cell-style="tableCellStyle" border stripe>
            <el-table-column prop="time" label="备份时间" width="180" />
            <el-table-column prop="size" label="文件大小" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <span :class="['status-badge', scope.row.status === '成功' ? 'status-success' : 'status-fail']">{{ scope.row.status }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="primary" link @click="handleDownload(scope.row)">下载</el-button>
                <el-button type="danger" link @click="deleteBackup(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="table-pagination"
            :current-page="backupPage.pageNum"
            :page-size="backupPage.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="backupData.length"
            layout="total, prev, pager, sizes, jumper"
            @size-change="val => { backupPage.pageSize = val; backupPage.pageNum = 1; }"
            @current-change="val => backupPage.pageNum = val"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="系统日志管理" name="logs">
        <div class="card-block">
          <div class="log-filter-form">
            <el-input v-model="logFilter.operator" placeholder="操作人" style="width: 180px; margin-right: 16px" />
            <el-date-picker v-model="logFilter.date" type="date" placeholder="年/月/日" style="width: 180px; margin-right: 16px" />
            <el-select v-model="logFilter.module" placeholder="模块" style="width: 180px; margin-right: 16px">
              <el-option label="客户管理" value="客户管理" />
              <el-option label="订单管理" value="订单管理" />
              <el-option label="用户管理" value="用户管理" />
              <el-option label="文件管理" value="文件管理" />
              <el-option label="系统管理" value="系统管理" />
            </el-select>
            <el-button type="primary" @click="handleLogQuery">查询</el-button>
            <el-button @click="handleLogClear">清空</el-button>
          </div>
        </div>
        <div class="card-block mt-4">
          <el-table :data="pagedLogs" class="settings-table" :header-cell-style="tableHeaderStyle" :cell-style="tableCellStyle" border stripe>
            <el-table-column prop="time" label="时间" width="180" />
            <el-table-column prop="operator" label="操作人" width="120" />
            <el-table-column prop="module" label="模块" width="120" />
            <el-table-column prop="content" label="操作内容" />
            <el-table-column prop="ip" label="IP地址" width="140" />
          </el-table>
          <el-pagination
            class="table-pagination"
            :current-page="logPage.pageNum"
            :page-size="logPage.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="filteredLogs.length"
            layout="total, prev, pager, sizes, jumper"
            @size-change="val => { logPage.pageSize = val; logPage.pageNum = 1; }"
            @current-change="val => logPage.pageNum = val"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  setup() {
    // 参数设置
    const params = ref([
      { code: 'PET_PARA_001', name: '时区', value: 'UTC+8', description: '时区设置', effectiveRange: '全局' },
      { code: 'PET_PARA_002', name: '语言', value: '中文', description: '语言设置', effectiveRange: '全局' },
      { code: 'PET_PARA_003', name: '主题颜色', value: '#409EFF', description: '主题颜色设置', effectiveRange: '全局' },
      { code: 'PET_PARA_004', name: '登录超时时间', value: '30分钟', description: '登录超时时间设置', effectiveRange: '全局' },
      { code: 'PET_PARA_005', name: '最大上传文件大小', value: '10MB', description: '最大上传文件大小设置', effectiveRange: '全局' },
    ]);
    const paramPage = reactive({ pageNum: 1, pageSize: 5 });
    const showParamDialog = ref(false);
    const editingParam = ref(null);
    const paramForm = reactive({ code: '', name: '', value: '', description: '', effectiveRange: '' });
    const paramDialogTitle = computed(() => editingParam.value ? '编辑参数' : '新增参数');
    const filteredParams = computed(() => params.value);
    const pagedParams = computed(() => filteredParams.value.slice((paramPage.pageNum-1)*paramPage.pageSize, paramPage.pageNum*paramPage.pageSize));
    function openAddParam() {
      editingParam.value = null;
      Object.assign(paramForm, { code: '', name: '', value: '', description: '', effectiveRange: '' });
      showParamDialog.value = true;
    }
    function editParam(row) {
      Object.assign(paramForm, row);
      editingParam.value = row;
      showParamDialog.value = true;
    }
    function saveParam() {
      if (!paramForm.code || !paramForm.name || !paramForm.value) {
        ElMessage.error('请填写必填项');
        return;
      }
      if (editingParam.value) {
        Object.assign(editingParam.value, paramForm);
        ElMessage.success('参数已更新');
      } else {
        params.value.unshift({ ...paramForm });
        ElMessage.success('新增参数成功');
      }
      showParamDialog.value = false;
    }
    function deleteParam(row) {
      ElMessageBox.confirm(`确定要删除参数 ${row.name} 吗？`, '确认删除', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        const idx = params.value.indexOf(row);
        if (idx !== -1) params.value.splice(idx, 1);
        ElMessage.success('参数已删除');
      });
    }

    // 备份与恢复
    const backupStrategy = reactive({ cycle: '每周', time: '02:00' });
    const backupData = ref([
      { time: '2025-06-29 02:00', size: '125.6 MB', status: '成功' },
    ]);
    const backupPage = reactive({ pageNum: 1, pageSize: 5 });
    const pagedBackups = computed(() => backupData.value.slice((backupPage.pageNum-1)*backupPage.pageSize, backupPage.pageNum*backupPage.pageSize));
    function handleBackup() {
      backupData.value.unshift({
        time: `${new Date().toISOString().slice(0, 16).replace('T', ' ')}`,
        size: `${(Math.random()*100+10).toFixed(1)} MB`,
        status: '成功',
      });
      ElMessage.success('已执行备份');
    }
    function handleRestore() {
      ElMessage.success('已恢复数据');
    }
    function handleDownload(row) {
      ElMessage.success('下载：' + row.time);
    }
    function deleteBackup(row) {
      const idx = backupData.value.indexOf(row);
      if (idx !== -1) backupData.value.splice(idx, 1);
      ElMessage.success('已删除备份');
    }

    // 日志管理
    const logFilter = reactive({ operator: '', date: '', module: '' });
    const logs = ref([
      { time: '2025-06-29 14:30', operator: '张小明', module: '客户管理', content: '新增客户信息', ip: '192.168.1.100' },
    ]);
    const logPage = reactive({ pageNum: 1, pageSize: 5 });
    const filteredLogs = computed(() => {
      return logs.value.filter(l =>
        (!logFilter.operator || l.operator.includes(logFilter.operator)) &&
        (!logFilter.module || l.module.includes(logFilter.module)) &&
        (!logFilter.date || l.time.startsWith(logFilter.date))
      );
    });
    const pagedLogs = computed(() => filteredLogs.value.slice((logPage.pageNum-1)*logPage.pageSize, logPage.pageNum*logPage.pageSize));
    function handleLogQuery() {
      logPage.pageNum = 1;
    }
    function handleLogClear() {
      logFilter.operator = '';
      logFilter.date = '';
      logFilter.module = '';
      logPage.pageNum = 1;
    }

    // 通用表格样式
    const tableHeaderStyle = () => ({ background: '#f8fafc', color: '#222', fontWeight: 600 });
    const tableCellStyle = () => ({ background: '#fff' });

    // tab切换
    const activeTab = ref('params');

    return {
      activeTab,
      params, paramPage, showParamDialog, editingParam, paramForm, paramDialogTitle, filteredParams, pagedParams,
      openAddParam, editParam, saveParam, deleteParam,
      backupStrategy, backupData, backupPage, pagedBackups, handleBackup, handleRestore, handleDownload, deleteBackup,
      logFilter, logs, logPage, filteredLogs, pagedLogs, handleLogQuery, handleLogClear,
      tableHeaderStyle, tableCellStyle
    };
  }
};
</script>

<style scoped>
.system-settings-root {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 0 0 40px 0;
}
.settings-tabs {
  background: #fff;
  border-radius: 0 0 8px 8px;
  box-shadow: 0 2px 8px 0 #f0f1f2;
  padding: 0 24px 24px 24px;
}
.card-block {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 #f0f1f2;
  padding: 24px;
  margin-bottom: 24px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}
.card-title {
  font-size: 20px;
  font-weight: 600;
}
.settings-table {
  margin-top: 8px;
  border-radius: 8px;
  overflow: hidden;
}
.table-pagination {
  margin-top: 16px;
  text-align: right;
}
.backup-strategy-form {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  align-items: center;
  margin-bottom: 8px;
}
.form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
.form-label {
  font-size: 15px;
  color: #555;
  min-width: 70px;
}
.form-btns {
  gap: 12px;
}
.status-badge {
  display: inline-block;
  padding: 2px 12px;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 500;
  color: #2ecc71;
  background: #e8f7e5;
}
.status-fail {
  color: #e74c3c;
  background: #fdeaea;
}
.status-success {
  color: #2ecc71;
  background: #e8f7e5;
}
.log-filter-form {
  display: flex;
  align-items: center;
  gap: 0;
  margin-bottom: 8px;
}
.mt-4 {
  margin-top: 24px;
}
.table-pagination >>> .el-pager li.is-active {
  background: #409EFF;
  color: #fff;
  border-radius: 4px;
}
.table-pagination >>> .el-pager li {
  border-radius: 4px;
}
</style>
